package com.beg.cant.controller;

import com.beg.cant.comment.result.Result;
import com.beg.cant.comment.utils.WechatSecurityHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


@RestController
@RequestMapping("/api")
public class FileUploadController {
    
    // 注入配置的存储路径
    @Value("${file.upload-dir}")
    private String uploadDir;
    @Value("${file.url}")
    private String url;
    @Autowired
    private WechatSecurityHelper wechatSecurityHelper;
    @PostMapping("/upload")
    public Result<String> uploadFile(
            @RequestParam("file") MultipartFile file) {
        
        // 1. 校验空文件[5](@ref)
        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }
        wechatSecurityHelper.checkImageSecurity(file);
        try {
            // 2. 生成UUID文件名[6,8](@ref)
            String originalName = file.getOriginalFilename();
            String extension = originalName.substring(originalName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + extension;
            
            // 3. 创建存储目录[8](@ref)
            File storageDir = new File(uploadDir);
            if (!storageDir.exists()) {
                storageDir.mkdirs();
            }
            
            // 4. 转存文件[2,5](@ref)
            File destFile = new File(uploadDir + File.separator + newFileName);
            file.transferTo(destFile);
            
            return Result.success(url +"image/"+ newFileName);
            
        } catch (IOException e) {
            return Result.error("上传失败：" + e.getMessage());
        }
    }
}